package com.lpb.spring.lpbspring.aop.proxy;

import com.lpb.spring.lpbspring.aop.advisor.Advisor;
import com.lpb.spring.lpbspring.ioc.BeanFactory;

import java.lang.reflect.Method;
import java.util.List;

/**
 * @ClassName AopProxyFactory
 * @Description TODO
 * @date 2022/12/9 01:11
 * @Version 1.0
 * @authoe linpengbo
 */
public class AopProxyFactory {

    public static AopProxy getAopProxy(String beanName, Object target, List<Advisor> advisorList, BeanFactory beanFactory){
        //这里判断如果被代理对象实现了接口 那么使用jdk动态代理 反之使用cglib代理
        if(isImplateInterface(target)){
           return new JdkProxy(target,advisorList,beanFactory);
        }
        return new CglibProxy(beanName,target,advisorList,beanFactory);
    }

    public static boolean isImplateInterface(Object target){
        Class<?> clazz = target.getClass();
        Class<?>[] interfaces = clazz.getInterfaces();
        if(interfaces==null||interfaces.length==0){
            return false;
        }

        for (Class<?> cla:interfaces) {
            Method[] methods = cla.getMethods();
            if(methods!=null&&methods.length>0){
                return true;
            }
        }
        return false;
    }

}
